import React, { useCallback, useLayoutEffect, useState } from 'react';
import {
  hideMenuButton,
  router,
  ScrollView,
  Text,
  View,
  Image,
  publishDps,
  showToast,
} from '@ray-js/ray';
import { IconFont } from '@/components';
import clsx from 'clsx';
import { useAppConfig } from '@/hooks/useAppConfig';
import { getStatusBarHeight, rpx2pxNum } from '@/utils';

import { Collapse, CollapseItem, Icon, SwipeCell, Switch } from '@ray-js/smart-ui';
import icons from '@/icons';
import Strings from '@/i18n';

import res from '@/res/images';
import {
  NormalTimerData,
  CycleTimerData,
  putTimerData,
  getRepeatStr,
  formatTimeString,
  encodeAllNormalTimer,
  encodeAllCycleTimer,
} from '@/utils/timer';
import useHandleJump from '@/hooks/useHandleJump';
import Styles from './TimerList.module.less';

interface LayoutProps {
  dataSource: NormalTimerData[] | CycleTimerData[];
  type: 'normal' | 'cycle';
  anotherSource: NormalTimerData[] | CycleTimerData[];
}

const pics = {
  normal: res.commontimer,
  cycle: res.looptimer,
};

export const formatTimeShowString = (time: number) => {
  const hours = Math.floor(time / 60);
  const minutes = time % 60;

  return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}`;
};

const getAreaName = (waterArea: number, dpsInfo: any) => {
  return dpsInfo[waterArea]?.name || waterArea.toString();
};

export function TimeList({
  type,
  dataSource,
  dpsInfo,
  anotherSource,
}: LayoutProps & { dpsInfo: any }) {
  console.log('🚀 ~ TimeList ~ dataSource:', dataSource, dpsInfo);
  const [isCollapsed, setIsCollapsed] = useState(true);

  const handleJump = useHandleJump();

  const renderNormalItem = (item: NormalTimerData, index: number) => (
    <View
      className={clsx(Styles.normalCell, { [Styles.lastCell]: index === dataSource.length - 1 })}
      onClick={() => handleJump(`addNormal?isEdit=true&id=${item.id}`)}
    >
      <View className={Styles.leftBox}>
        <View>
          <Text className={clsx(Styles.timeText, !item.power && Styles.timeTextClose)}>
            {formatTimeShowString(item.startTime)}
          </Text>
        </View>
        <View
          className={Styles.waterInfoBox}
          style={{
            color: item.power ? '#8e8e8e' : '#c5c5c5',
          }}
        >
          开关:{getAreaName(item.waterArea, dpsInfo)}
        </View>
        <View
          className={Styles.waterInfoBox}
          style={{
            color: item.power ? '#8e8e8e' : '#c5c5c5',
          }}
        >
          灌溉时间:{formatTimeString(item.waterTime)}
        </View>

        <View
          className={Styles.loopsBox}
          style={{
            color: item.power ? '#8e8e8e' : '#c5c5c5',
          }}
        >
          <Text>{item.repeatStr}</Text>
        </View>
      </View>

      <View className={Styles.rightBox}>
        <Switch
          checked={item.power}
          onChange={() => {
            putTimerData({
              key: type === 'cycle' ? 'cycleTiming' : 'normalTiming',
              data: {
                ...item,
                power: !item.power,
              },
              isEdit: true,
              normalDataSource: (type === 'normal'
                ? dataSource
                : anotherSource) as NormalTimerData[],
              cycleDataSource: (type === 'cycle' ? dataSource : anotherSource) as CycleTimerData[],
              callback: (isReject: boolean, conflictTip = '') => {
                if (isReject) {
                  showToast({
                    title: conflictTip,
                    icon: 'error',
                  });
                } else {
                  showToast({
                    title: Strings.getLang('save_success'),
                  });
                }
              },
            });
          }}
          stopClickPropagation
        />
      </View>
    </View>
  );

  const renderLoopItem = (item: CycleTimerData, index: number) => (
    <View
      className={clsx(Styles.loopCell, { [Styles.lastCell]: index === dataSource.length - 1 })}
      onClick={() => handleJump(`addCircle?isEdit=true&id=${item.id}`)}
    >
      <View className={Styles.leftBox}>
        <View>
          <Text className={clsx(Styles.timeText, !item.power && Styles.timeTextClose)}>
            {formatTimeShowString(item.startTime)} - {formatTimeShowString(item.endTime)}
          </Text>
        </View>
        <View
          className={Styles.waterInfoBox}
          style={{
            color: item.power ? '#8e8e8e' : '#c5c5c5',
          }}
        >
          开关:{getAreaName(item.waterArea, dpsInfo)}
        </View>
        <View
          className={Styles.waterInfoBox}
          style={{
            color: item.power ? '#8e8e8e' : '#c5c5c5',
          }}
        >
          灌溉时间:{formatTimeString(item.waterTime)} - 暂停时间:{formatTimeString(item.pauseTime)}
        </View>
        <View
          className={Styles.loopsBox}
          style={{
            color: item.power ? '#8e8e8e' : '#c5c5c5',
          }}
        >
          <Text>{item.repeatStr}</Text>
        </View>
      </View>

      <View className={Styles.rightBox}>
        <Switch
          checked={item.power}
          onChange={() => {
            putTimerData({
              key: type === 'cycle' ? 'cycleTiming' : 'normalTiming',
              data: {
                ...item,
                power: !item.power,
              },
              isEdit: true,
              normalDataSource: (type === 'normal'
                ? dataSource
                : anotherSource) as NormalTimerData[],
              cycleDataSource: (type === 'cycle' ? dataSource : anotherSource) as CycleTimerData[],
              callback: (isReject: boolean, conflictTip = '') => {
                if (isReject) {
                  showToast({
                    title: conflictTip,
                    icon: 'error',
                  });
                } else {
                  showToast({
                    title: Strings.getLang('save_success'),
                  });
                }
              },
            });
          }}
          stopClickPropagation
        />
      </View>
    </View>
  );

  const deleteTime = del => {
    console.log('🚀 ~ deleteTime ~ del:', del);
    const newData = dataSource.filter(item => item.id !== del.id);

    if (type === 'normal') {
      publishDps({
        general_timing: encodeAllNormalTimer(newData),
      });
    }

    if (type === 'cycle') {
      publishDps({
        cycle_timing1: encodeAllCycleTimer(newData).circle1,
        cycle_timing2: encodeAllCycleTimer(newData).circle2,
      });
    }
  };

  return (
    <View className={Styles.app}>
      <View
        className={clsx(Styles.titleBox, { [Styles.lastCell]: !isCollapsed })}
        onClick={() => setIsCollapsed(!isCollapsed)}
      >
        <View className={Styles.titleLeftBox}>
          <View className={Styles.iconBox}>
            <Image className={Styles.timerIcon} src={pics[type]} />
          </View>

          <View>
            <Text>{Strings.getLang(`${type === 'cycle' ? 'cycleTime' : 'normalTime'}`)}</Text>
          </View>
        </View>

        <View className={Styles.titleRightBox}>
          <Icon
            name={icons.slideArrow}
            className={clsx(Styles.rotateIcon, { [Styles.rotate]: !isCollapsed })}
          />
        </View>
      </View>

      <View className={clsx(Styles.collapse, { [Styles.collapsed]: isCollapsed })}>
        {dataSource.map((item: NormalTimerData | CycleTimerData, index) => (
          <SwipeCell
            key={item.id}
            rightWidth={65}
            className={Styles.swipeCell}
            slot={{
              right: (
                <View
                  className={Styles.deleteIcon}
                  onClick={() => {
                    deleteTime(item);
                  }}
                >
                  <Image src={res.deletepic} className={Styles.deleteImg} />
                </View>
              ),
            }}
          >
            <View className={Styles.cellBox}>
              {dpsInfo.some(dp => dp.areaInTimer === item.areaStr && dp.isOffLine) ? (
                <View className={Styles.offLineBox}>
                  <Image src={res.timerOffLine} className={Styles.offLineImg} />
                  <Text className={Styles.offLineText}>
                    该设备已经离线，定时将会保留直到下一次上线，您可以右滑删除该定时
                  </Text>
                </View>
              ) : null}

              {type === 'normal'
                ? renderNormalItem(item, index)
                : renderLoopItem(item as CycleTimerData, index)}
            </View>
          </SwipeCell>
        ))}
      </View>
    </View>
  );
}

export default TimeList;
